import http from "axios";
import qs from "qs";
import Internet from './config'
/**
 * 公用参数
 ---------------------*/
let internetFml:string='http://zays.gakm.net' //开发使用域名
let successCode:string="0" //成功code
let invalidToken:string="601" //token失效code
let specialNeed:string="613" //特殊情况

/**域名
 *
---------------------*/
const URL:string =process.env.NODE_ENV == "production" ? internetFml : "/api";

/** 拦截器
 *
---------------------*/
http.interceptors.request.use(
  config=>{
    config.baseURL=URL
    config.timeout=5000
    let token:string=sessionStorage.getItem('Token')
    if(token){
      config.headers={
        'Authentication':token,
        'Content-Type':'application/x-www-form-urlencoded'
      }
    }
    return config;
  },error=>{
    return Promise.reject(error);
  }
);
http.interceptors.response.use(
  response=>{
    return response;
  },error=>{
    return Promise.reject(error);
  }
);

/**下载
 *
 ------------------------*/
const DownLoadFile=function({apiUrl,params={}}){
  try{
    window.location.href=apiUrl+"?" + qs.stringify(params)
  }catch(e){
    alert("文件下载失败")
  }
}

/**
 * 请求处理函数
 ------------------------*/
const fetchService=async function(method,apiUrl,params){
  let that=this
  try{
    let res
    if(method=='get'){
     res=await http.get(apiUrl,{params})
    }else if(method=='post'){
      res=await http.post(apiUrl,qs.stringify(params))
    }else if(method=='delete'){
      res=await http.delete( apiUrl, { data: qs.stringify(params) })
    }else if(method=='put'){
      res=await http.put(apiUrl, qs.stringify(params))
    }else{
      return  Promise.resolve([new Error('程序出错')])
    }
    const responesCode=String(res.data.code)
    if(responesCode==successCode){
      return Promise.resolve([null,res.data])
    }else if(responesCode==invalidToken){
      sessionStorage.clear();
      window.location.href=internetFml
      return Promise.resolve([new Error(res.data.message||"登录失效，请重新登录"),null])

    }else if(responesCode==specialNeed){
      that.$nuxt.$route.push({path:'/nav_menu'})
    }else{
     return Promise.resolve([new Error(res.data.message||"请求出错"),null])
    }
  }catch(err){
    return Promise.resolve([new Error(err.message||"请求超时"),null])
  }
}
/**
 * get请求
 -----------------------*/
const Get=async function({apiUrl,params={}}){
  return fetchService('get',apiUrl,params)
}
/**
 * post请求
 -----------------------*/
const Post=async function({apiUrl,params={}}){
  return fetchService('post',apiUrl,params)
}
/**
 * delete请求
 -----------------------*/
const Delete=async function({apiUrl,params={}}){
  return fetchService('delete',apiUrl,params)
}
/**
 * put请求
 -----------------------*/
const Put=async function({apiUrl,params={}}){
  return fetchService('put',apiUrl,params)
}

class Api{

  fmlDomain:any=internetFml
  fmlUpload:any=internetFml+Internet.upload
  /**
   * get请求
  ------------------*/
  fetchGet(params:any,api:string,urlparam:boolean){
    const data={
      apiUrl:urlparam?Internet[api]+'/'+params.id:Internet[api],
      params
    }
    return Get(data)
  }
  /**
   * Post 请求
   -----------------*/
  fetchPost(params:any,api:string,urlparam:boolean){
    const data={
      apiUrl:urlparam?Internet[api]+'/'+params.id:Internet[api],
      params
    }
    return Post(data)
  }
  /**
   * Delete请求
   */
  fetchDelete(params:any,api:string,urlparam:boolean){
    const data = {
      apiUrl:urlparam?Internet[api]+'/'+params.id:Internet[api],
      params
    };
    return Delete(data);
  }
  /**
   * Put请求
   */
  fetchPut(params:any,api:string,urlparam:boolean) {
    const data = {
      apiUrl:urlparam?Internet[api]+'/'+params.id:Internet[api],
      params
    }
    return Put(data)
  }
  /**
   * download
   */
  fetchDownLoad(params:any,api:string){
    const data={
      apiUrl:Internet[api],
      params
    }
    return DownLoadFile(data)
  }
}

 const fetchApi=new Api()
 export default fetchApi
